<?php
namespace yitongpay\lib;

use think\Exception;
use think\facade\Config;
use think\facade\Log;


/**
 * 
 * 接口访问类，包含所有微信支付API列表的封装，类中方法为static方法，
 * 每个接口有默认超时时间（除提交被扫支付为10s，上报超时时间为1s外，其他均为6s）
 * @author widyhu
 *
 */
class YitongPayApi
{
	// 查询接口
	public static function orderQuery($data)
	{
		$url = Config::get('yitong.host').'/NetPay/MerOrderQuery.action';
        $res = [
            'merchantId' => Config::get('yitong.merchantId'),
            'merOrderNum' => $data['merOrderNum'],
            'tranDate' => $data['tranDate']
        ];
        $input = new ToolServer();
        $input->SetValues($res);
        $input->getSignValue($res['merchantId'].'|'.$res['merOrderNum'].'|'.$res['tranDate']);
        if(Config::get('yitong.log')) {
            Log::record('=============start 查询订单=====================');
            Log::record($res);
            Log::record($url);
            Log::record($input->GetValues());
        }
        return self::PostCURL($url, $input->GetValues(), true);
	}

	// 获取短信签约验证码
	public static function sendMessage($data)
    {
        $url = Config::get('yitong.host').'/NetPay/sendMessage.action';
        $res = [
            'bussId' => 'ONL0022',
            'cardCvn2' => $data['cardCvn2'] ? SecurityUtils::encrypt($data['cardCvn2']) : '',
            'cardExpire' => $data['cardExpire'] ? SecurityUtils::encrypt($data['cardExpire']) : '',
            'certNo' => SecurityUtils::encrypt($data['certNo']),
            'merchantId' => Config::get('yitong.merchantId'),
            'merOrderNum' => $data['merOrderNum'],
            'tranAmt' => (int) $data['tranAmt'],
            'userAcctNo' => SecurityUtils::encrypt($data['userAcctNo']),
            'userId' => $data['userId'],
            'userIp' => $data['userIp'],
            'userName' => SecurityUtils::bin2hex($data['userName']),
            'userPhone' => SecurityUtils::encrypt($data['userPhone'])
        ];
        $input = new ToolServer();
        $input->SetValues($res);
        $input->getSign(false, '&');
        if(Config::get('yitong.log')) {
            Log::record('=============start 获取短信签约验证码=====================');
            Log::record($data);
            Log::record($url);
            Log::record($input->GetValues());
        }
        return self::PostCURL($url,$input->GetValues());
    }

    // 支付签约接口
    public static function quickSign($data)
    {
        $url = Config::get('yitong.host').'/NetPay/quickSign.action';
        $res = [
            'bussId' => 'ONL0022',
            'certNo' => SecurityUtils::encrypt($data['certNo']),
            'frontUrl' => 'http://card.test.jxqianbao.com',
            'merchantId' => Config::get('yitong.merchantId'),
            'merOrderNum' => $data['merOrderNum'],
            'tranAmt' => (int) $data['tranAmt'],
            'userAcctNo' => SecurityUtils::encrypt($data['userAcctNo']),
            'userName' => SecurityUtils::bin2hex($data['userName']),
            'userPhone' => SecurityUtils::encrypt($data['userPhone']),
        ];

        $input = new ToolServer();
        $input->SetValues($res);
        $input->getSign(false, '&');
        $input->SetValues(['smsKey' => $data['smsKey']]);
        $input->SetValues(['smsCode' => $data['smsCode']]);
        $input->SetValues(['smsTranId' => $data['smsTranId']]);
        if(Config::get('yitong.log')) {
            Log::record('=============start 验证签约验证码=====================');
            Log::record($url);
            Log::record($data);
            Log::record($input->GetValues());
        }
        return self::PostCURL($url,$input->GetValues());
    }

    // 快捷付银联S2通道请求
    public static function synonymNamePay($data, $user_credit, $tms, $ip)
    {
        $url = Config::get('yitong.host').'/NetPay/SynonymNamePay.action';
        $res = [
            'version' => '1.0.0',
            'transCode' => '8888',
            'merchantId' => Config::get('yitong.merchantId'),
            'merOrderNum' => $data['order_number'],
            'bussId' => 'ONL0022',
            'tranAmt' => (int) $data['amount'] * 100,
            'sysTraceNum' => $data['order_number'].'_01',
            'tranDateTime' => date('YmdHis', $tms),
            'currencyType' => '156',
            'merURL' => 'http://spread.test.jxqianbao.com/',
            'backURL' => '',
            'orderInfo' => '',
            'userId' => $data['uid'],
        ];
        if($user_credit['credit_valid_date']) {
            list($m,$y) = explode('/', $user_credit['credit_valid_date']);
        }
        $param = [
            'userNameHF' => SecurityUtils::bin2hex($user_credit['name_on_card']),
            'quickPayCertNo' => $user_credit['id_number'],
            'arrviedAcctNo' => $data['savings_card_no'],
            'arrviedPhone' => $data['savings_mobile'],
            'arrviedBankName' => $data['bank_name'],
            'userPhoneHF' => $user_credit['credit_mobile'],
            'userAcctNo' => $user_credit['full_card_number'],
            'cardCvn2' => $user_credit['credit_verification_code'],
            'cardExpire' => $user_credit['credit_valid_date'] ? $m.$y : '',
            'userIp' => $ip,
            'protocolNo' => $data['tran_id'],
            'bankId' => '888880170122900',
            'stlmId' => '',
            'entryType ' => 1,
            'attach' => '',
            'reserver1' => $data['poundage'], // 手续费
            'reserver2' => '',
            'reserver3' => '',
            'reserver4' => 7,
        ];
        $input = new ToolServer();
        $input->SetValues(array_merge($res, $param));
        $buff = '';
        foreach($res as $value) {
            $buff .= '|' .$value;
        }
        $buff = trim($buff, '|');
        $input->getSignValue($buff);
        if(Config::get('yitong.log')) {
            Log::record('=============start 支付签约=====================');
            Log::record($url);
            Log::record($input->GetValues());
        }

        return self::PostCURL($url,$input->GetValues(), true);
    }

	// post请求
    public static function PostCURL($url, $post_data, $t = false)
    {
        try{
            $ch         = curl_init();//初始化一个会话
            /* 设置验证方式 */
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//设置返回结果为流
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//设置请求超时时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);//设置响应超时时间
            /* 设置通信方式 */

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            if($post_data) {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//使用urlencode格式请求
            }

            $result = curl_exec($ch);//获取返回结果集
            if(Config::get('yitong.log')) {
                Log::record('=============start 接口返回=====================');
                Log::record($result);
            }
            if (curl_errno($ch) !== 0) //网络问题请求失败
            {
                $result = [
                    'respMsg' => '网络请求超时',
                    'respCode' => '5000',
                ];
                curl_close($ch);//关闭请求会话
                return $result;
            }else {
                $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($statusCode != 200)//域名问题请求失败或不存在返回结果
                {
                    $result = [
                        'respMsg' => '网络请求超时',
                        'respCode' => '5000',
                    ];
                }else{
                    if(!isset($result['respCode'])) {
                        if($result == 'none') {
                            $result = [
                                'respMsg' => '订单查询失败',
                                'respCode' => '9999',
                            ];
                            return $result;
                        }
                    }
                }
                return self::returnMsg($result, $t);
            }
        }catch (Exception $e){
            $result = [
                'respMsg' => '网络请求超时',
                'respCode' => '5000',
            ];
            return $result;
        }
    }

    public static function loadFile($time)
    {
        $data = [
            'merchantId' => Config::get('yitong.merchantId'),
            'tranDate' => $time
        ];
        $url = Config::get('yitong.host').'/NetPay/loadTradeFile.action';
        $input = new ToolServer();
        $input->SetValues($data);
        $input->getSignValue($data['merchantId'].'|'.$data['tranDate']);
        $result =  self::PostCURL($url,$input->GetValues(), true);
        return $result;
    }

    private static function returnMsg($data, $t = false)
    {
        if($t == false) {
            return json_decode($data, true);
        }
        $data = explode('&', $data);
        $result = [];
        foreach ($data as $value) {
            list($key,$value) = explode('=', $value);
            if($key == 'reserver3') {
                if($t && $value != '') {
                    $value = SecurityUtils::hexToStr($value);
                }
            }
            $result[$key] = $value;
        }
        return $result;
    }

}

